/**
* @Author: 李晨光
* @Date: 2019/12/4
* @Version: 1.0
* @Last Modified by: 李晨光
* @Last Modified time: 2019/12/4
**/
<comment>
  属性：multiple 类型 ： Boolean 默认值： false
  属性：lists 类型 ： Array 默认值： [] 数据格式： [{label: '1',
  value: '1',
  disabled: false,
  checked: false,
  hasChecked: true,
  hasChildren: true
  }]
  v-model : [{label: '1',
  value: '1',
  disabled: false,
  checked: false,
  hasChecked: true,
  hasChildren: true
  }]
  事件：
  change 值发生变化
  expand 展开下级
  unexpand 收起下级
</comment>
<template>
  <div id="UserTreeThrough">
    <!--组织-->
    <div v-show="tab == 'org'" class="org-box">
      <Search ref="orgSearch" :lists="searchLists" :open="orgSearch" @confirm="searchConfirm" @search="searchOrg"
              @open="openOrgSearch" @close="closeOrgSearch">
        <!--<template slot="search-item" slot-scope="test">-->
        <!--</template>-->
      </Search>
      <!--顶部面包屑导航 选择结果-->
      <mu-list>
        <mu-list-item style="width: 100%;overflow-x: auto;">
          <mu-breadcrumbs divider="—" tag="li">
            <mu-icon value="chevron_right" slot="divider"></mu-icon>
            <mu-breadcrumbs-item v-for="item in navs" :key="item.label" :disabled="item.disabled">
              <li @click="unexpand(item)">{{item.label}}</li>
            </mu-breadcrumbs-item>
          </mu-breadcrumbs>
        </mu-list-item>
      </mu-list>
      <!--数据列-->
      <div class="list" style="height: calc(100vh - 1.5rem);overflow: auto;margin-top: 10px">
        <mu-list>
          <mu-list-item v-for="(list, index) in lists" button style="margin-bottom: 1px;" :key="index"
                        @click="select(list, 'org')">
            <template v-if="list.hasChecked">
              <mu-checkbox v-if="multiple" v-model="list.checked" :value="list.value" :label="list.label"></mu-checkbox>
              <mu-radio v-else v-model="orgCheck" :value="list.value" :label="list.label"></mu-radio>
            </template>
            <mu-list-item-title v-if="!list.hasChecked">{{list.label}}</mu-list-item-title>
            <div style="width: .2rem;position: absolute;right: 1rem;" v-if="!list.hasChecked">
              <i v-show="orgCheck == list.value" class="iconfont iconxuanze" style="color: #24D90C;"></i>
            </div>

            <mu-list-item-action @click.stop="expand(list)" v-if="list.hasChildren">
              <i class="iconfont iconzuzhi"></i>
              下级
            </mu-list-item-action>
          </mu-list-item>
        </mu-list>
      </div>
    </div>
    <!--人员-->
    <div v-show="tab == 'user'" class="ly_flex user-box">
      <template v-if="orgType == '1'">
        <ul class="contact">
          <li v-for="(type,index) in contactTypes" :class="activeType ==  type.value ? 'active' : ''" @click="tabType(type,orgSelect[0])" :key="index">
            {{type.label}}
          </li>
        </ul>
        <div style="width: calc(100% - 0.8rem);padding: .1rem .14rem;box-sizing: border-box">
          <Search ref="search" :lists="userLists" :open="userSearch" @confirm="searchConfirm" @search="searchUser"
                  @open="openUserSearch" @close="closeUserSearch">
            <mu-list slot="search-btn" class="search-list">
              <mu-list-item
                style="background:rgba(248,248,248,1);text-align: center;align-items: center;display: flex;justify-content: center">
                <div class="search-user" @click="openUserSearch">
                  <mu-icon value="search"/>
                  按名称搜索
                </div>
              </mu-list-item>
            </mu-list>
            <!--<template slot="search-item" slot-scope="test">-->
            <!--</template>-->
          </Search>
          <!--数据列-->
          <div class="list" style="overflow: auto;margin-top: 10px"
               :style="{height: multiple ? 'calc(100vh - 1.8rem)' : 'calc(100vh - 1.3rem)'}">
            <mu-list>
              <mu-list-item v-for="(list, index) in users" button style="margin-bottom: 1px;" :key="index"
                            @click="select(list, 'user')">
                <template v-if="list.hasChecked && false">
                  <mu-checkbox v-if="multiple" v-model="list.checked" :value="list.value"
                               :label="list.label"></mu-checkbox>
                  <mu-radio v-else v-model="check" :value="list.value" :label="list.label"></mu-radio>
                </template>
                <mu-list-item-title v-if="!list.hasChecked || true">{{list.label}}</mu-list-item-title>
                <div style="width: .2rem;position: absolute;right: .1rem;">
                  <i v-show="multiple ? checked.find(i => i.value == list.value) : check == list.value"
                     class="iconfont iconxuanze" style="color: #24D90C;"></i>
                </div>
              </mu-list-item>
            </mu-list>
          </div>
        </div>
      </template>
      <template v-if="orgType == '0'">
        <mt-index-list>
          <mt-index-section :index="index" v-for="(item, index) in users" :key="index">
            <mt-cell v-for="(child, index) in item" :key="index" >
              <div style="width: 100%;position: relative;height: .48rem;" class="ly_flex ly_flex_ali_center ly_flex_just_between" @click="select(child,'user')">
                <div>
                  {{child.label}}
                </div>
                <div style="width: .2rem;height: .48rem;position: absolute;right: .1rem;top:0 ;" class="ly_flex ly_flex_ali_center ly_flex_just_between">
                  <i v-show="multiple ? checked.find(i => i.value == child.value) : check == child.value"
                     class="iconfont iconxuanze" style="color: #24D90C;"></i>
                </div>
              </div>

            </mt-cell>
          </mt-index-section>
        </mt-index-list>
      </template>

    </div>
    <!--选择结果-->
    <mu-list class="fiexd-b" v-if="multiple && tab == 'user'">
      <mu-list-item>
        <span class="primary-color">已选: {{checked.length}}</span>
        <mu-button color="primary" @click="confirm">
          确 定
        </mu-button>
      </mu-list-item>
    </mu-list>
  </div>
</template>

<script>
  import Search from "@/search/Search.vue"
  let pinyin = require('js-pinyin')
  pinyin.setOptions({checkPolyphone: false, charCase: 0});
  export default {
    name: 'UserTreeThrough',
    components: {
      Search,
    },
    props: {
      // all---所有人
      // org---组织下所有人
      // project---项目下所有人
      // contact---参建单位下所有人
      // org-project---组织+项目所有人
      // project-contact---项目+参建单位所有人
      // org-project-contact---组织+项目+参建单位所有人
      dataScope: {
        type: String,
        default: 'all'
      },
      contactType: {
        type: String,  //  '1,2,3'
        default: '1,2,3'
      },
      // 是否多选
      multiple: {
        type: Boolean,
        default: true
      },
      // 原数据 数组
      lists: {
        type: Array,
        default: () => {
          return []
        }
      },
      // 选择结果
      checked: {
        type: Array,
        default: () => {
          return []
        }
      }
    },
    model: {
      prop: "checked",
      event: "change"
    },
    data() {
      return {
        api: {
          getUserApi: '/safety/users',
          getUserByCategoryApi: '/safety/corp/users',
          getUserDataApi: '/safety/project/users'
        },
        allChecked: false,
        check: '',
        orgCheck: '',
        checkedString: '',
        resLists: [],
        checkedArr: [],
        orgSelect: [],
        navs: [
          {
            label: '组织',
            value: 'org',
            disabled: true
          }],
        contactTypes: [],
        contactTypesInit: [
          {label: '项目', value: '0'},
          {label: '分包单位', value: '1'},
          {label: '业主单位', value: '2'},
          {label: '监理单位', value: '3'},
        ],
        activeType: 0,
        // 搜索结果
        searchLists: [],
        userLists: [],
        tab: 'org',
        users: [],
        orgSearch: false,
        userSearch: false,
        orgType: '0'
      }
    },
    computed: {},
    created() {
      let userInfo = this.$A.GS("userInfo")
      if(userInfo['userType'] == 2){
        this.api.getUserDataApi = "/safety/project/corpUsers"
      }
    },
    mounted() {
    },
    watch: {
      lists: {
        handler(newVal, oldVal) {
          this.resLists = newVal
        },
        immediate: true,
        deep: true
      },
      checked: {
        handler(newVal, oldVal) {
          this.checkedArr = newVal
          if (this.checkedArr.length) {
            this.check = this.checkedArr[0].value
          } else {
            this.check = ''
          }
        },
        immediate: true,
        deep: true
      },
    },
    methods: {
      // 选择选项
      select(item, type) {
        let canNextStatus = true
        if (type == 'org') {
          if(item.type == '0') {
            if(this.dataScope == 'project') {
              this.$A.MS('只能选择项目下的人员')
              canNextStatus = false
              return
            }
            if(this.dataScope == 'contact') {
              this.$A.MS('只能选择参建单位下的人员')
              canNextStatus = false
              return
            }
            if(this.dataScope == 'project-contact') {
              this.$A.MS('只能选择项目和参建单位下的人员')
              canNextStatus = false
              return
            }
            this.contactTypes = this.contactTypesInit
          }else{
            canNextStatus = true
            if(this.dataScope == 'project' || this.dataScope == 'org-project') {
             this.contactTypes = [{label: '项目', value: '0'}]
            }else if(this.dataScope == 'contact' || this.dataScope == 'project-contact') {
              this.contactTypes = []
              this.contactType.split(',').forEach(type => {
                if(this.contactTypesInit.find(i => i.value == type)) {
                  this.contactTypes.push(this.contactTypesInit[this.contactTypesInit.findIndex(i => i.value == type)])
                }
              })
              if(this.dataScope == 'project-contact') {
                this.contactTypes.unshift({label: '项目', value: '0'})
              }
            }else if(this.dataScope == 'all') {
              this.contactTypes = this.contactTypesInit
            }
          }
          if(canNextStatus) {
            console.log(this.contactTypes)
            this.orgCheck = item.value
            this.orgType = item.type
            this.$set(this.orgSelect, 0, item)
            this.$emit('orgChange', this.orgSelect)
            this.tab = 'user'

            this.tabType(this.contactTypes[0],item)
          }
        } else {
          if (this.multiple) {
            item.checked = !item.checked
            if (item.checked) {
              !this.checkedArr.find(i => i.value == item.value) && this.checkedArr.push(item)
            } else {
              this.checkedArr.splice(this.checkedArr.findIndex(i => i.value == item.value), 1)
            }
          } else {
            this.check = item.value
            this.$set(this.checkedArr, 0, item)
          }

          this.$emit('change', this.checkedArr)
          if (this.multiple) {
            let res = []
            this.checkedArr.length && this.checkedArr.forEach((item, index) => {
              res.push(item.label)
              this.checkedString = res.join(',')
            })
          } else {
            this.$emit('confirm', this.checkedArr)
            this.tab = 'user'
          }
        }
      },
      /**
       * 展开下级  通过监听expand事件在父组件获取下级数据
       * @param item
       */
      expand(item) {
        if(!this.navs.find(i => i.value == item.value)) {
          this.navs.push({
            label: item.label,
            value: item.value,
            disabled: true,
          })
          this.navs[0].disabled = false
          this.navs[this.navs.length - 1].disabled = true
          this.$emit('expand', item)
        }

      },
      unexpand(item) {
        this.navs.splice(this.navs.findIndex(i => i.value == item.value) + 1)
        this.$emit('unexpand', item)
      },
      // 选择结果确认
      confirm() {
        this.tabBox('org')
        console.log(222)
        this.$emit('confirm', this.checkedArr)
      },
      openOrgSearch() {
        this.searchLists = []
        this.orgSearch = true
      },
      closeOrgSearch() {
        this.orgSearch = false
      },
      openUserSearch() {
        this.userLists = []
        this.userSearch = true
      },
      closeUserSearch() {
        this.userSearch = false
      },
      // 搜索结果点击确认回调
      searchConfirm(ev) {
        this.closeOrgSearch()
        this.$emit('confirm', ev)
      },
      // 搜索组织回调
      searchOrg(ev) {
        let orgInfo = this.$A.GS('orgInfo')
        this.$A.Go('post', this.api.getUserDataApi, {
          "obj": {
            "category": "-1",
            "corpId": "",
            "userName": ev,
            "name": ev,
            "projectId": orgInfo.orgId,
            "userId": '',
          },
        })
          .then(response => {
            Util.processRes(response, () => {
              this.searchLists = this.dealData(response.body,'id', 'fullName')
              console.log(this.userLists)
            });
            Util.processError(this, response);
          })
          .catch(err => {
            console.log(err)
          });
      },
      // 搜索组织人员
      searchUser(ev) {
        let category = null
        if(this.activeType == 0) {
          category = 0
        }else if(this.activeType == 1) {
          category = 1
        }else if(this.activeType == 2) {
          category = 2
        }else if(this.activeType == 3) {
          category = 3
        }
        this.$A.Go('post', this.api.getUserDataApi, {
          "obj": {
            "category": category,
            "corpId": "",
            "name": ev,
            "userName": ev,
            "projectId": this.orgSelect[0].value,
            "userId": '',
          },
        })
          .then(response => {
            Util.processRes(response, () => {
              this.userLists = this.dealData(response.body,'id', 'fullName')
            });
            Util.processError(this, response);
          })
          .catch(err => {
            console.log(err)
          });

      },
      // 切换参建类型
      tabType(type, prop) {
        this.activeType = type.value
        if(prop.type != '0') {
          if(this.activeType != 0) {
            this.getUserByCategory({projectId: prop.value,category: this.activeType})
          }else{
            this.getUser({
              projectId: prop.value
            })
          }
        }else{
          this.getUser({
            orgId: prop.value
          })
        }

      },
      // 切换类型
      tabBox(str) {
        this.tab = str
      },
      getUser(props = {}) {
        this.$A.Go('post', this.api.getUserApi, {
          "obj": props,
          "pageNo": -1,
          "pageSize": 10
        })
          .then(response => {
            Util.processRes(response, () => {
              if(this.orgType == '0') {
                this.users = this.sortUsers(this.dealData(response.body, 'id', 'fullName'))
              }else{
                this.users = this.dealData(response.body, 'id', 'fullName')
              }
            });
            Util.processError(this, response);
          })
          .catch(err => {
            console.log(err)
          });
      },
      getUserByCategory(props = {}) {
        this.$A.Go('post', this.api.getUserByCategoryApi, {
          "obj": props,
          "pageNo": -1,
          "pageSize": 10
        })
          .then(response => {
            Util.processRes(response, () => {
              this.users = this.dealData(response.body, 'id', 'fullName')
            });
            Util.processError(this, response);
          })
          .catch(err => {
            console.log(err)
          });
      },
      dealData(data,value = '', label = '') {
        let arr = []
        data.length && data.forEach((item) => {
          let obj = {}
          obj = item
          obj.value = item[value]
          obj.label = item[label]
          obj.type = item['type']
          obj.hasChildren = true
          obj.hasChecked = false
          obj.disabled = true
          arr.push(obj)
        })
        return arr
      },
      sortUsers(data) {
        let arr = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
        let res = {}
        data.forEach((item,index) => {
          let letter = pinyin.getFullChars(item.label.charAt(0)[0].toUpperCase()).substring(0,1)
          console.log(letter)
          if(arr.indexOf(letter) > -1) {
            if(res[letter]) {
              res[letter].push(item)
            }else{
              res[letter] = [item]
            }
          }else{
            if(res['#']) {
              res[letter].push(item)
            }else{
              res['#'] = [item]
            }
          }
        })
        return res
      }
    },
    destroyed() {
    }
  }
</script>

<style lang="scss">
  #UserTreeThrough{
    .org-box .list .mu-item-title {
      width: 2.3rem !important;
      flex: unset;
    }

    .user-box .list .mu-item-title {
      width: 2.1rem !important;
      flex: unset;
    }

    .mu-radio-label {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 2.3rem;
      font-size: 0.15rem;
      font-weight: 400;
      color: rgba(61, 61, 61, 1);
      line-height: 0.21rem;
    }

    .mu-item {
      padding: 0 14px;
      height: .55rem;
      justify-content: space-between;
    }

    .mu-list {
      padding: 0;
    }

    .mu-list > li {
      background: #fff;
    }

    .mu-item-action.is-more {
      padding: 0 14px;
      min-width: unset;
      width: .9rem;
      position: absolute;
      right: 0;
      flex-direction: row;
      align-items: center;
      &:after {
        content: '';
        position: absolute;
        left: 0;
        height: .24rem;
        border-left: 2px solid #f0f0f0;

      }

    }

    .mu-breadcrumbs > li {
      font-size: 0.15rem;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: rgba(255, 138, 27, 1);
      .mu-icon {
        font-size: .2rem;
      }
    }

    .mu-breadcrumbs-divider {
      padding: 0 .05rem;
      color: rgba(0, 0, 0, .38);
    }

    .fiexd-b {
      border-top: 1px solid #f8f8f8;
      position: fixed;
      bottom: 0;
      left: 0;
      padding: 0;
    }

    .search {
      width: 3.47rem;
      height: 0.33rem;
      background: rgba(248, 248, 248, 1);
      border-radius: 0.83rem;
      font-size: 0.13rem;
      font-weight: 400;
      color: rgba(140, 140, 140, 1);
      text-align: center;
      align-items: center;
      display: flex;
      justify-content: center
    }

    .search-user {
      width: 2.68rem;
      height: 0.33rem;
      padding: .1rem .14rem;
      background: rgba(235, 235, 235, 1);
      border-radius: 0.04rem;
      font-size: 0.13rem;
      font-weight: 400;
      color: rgba(140, 140, 140, 1);
      line-height: 0.18rem;
      text-align: center;
      align-items: center;
      display: flex;
      justify-content: start;
    }

    .contact {
      width: .8rem;
      background: #fff;
      li {
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
        height: 0.45rem;
        font-size: 0.13rem;
        font-weight: 400;
        color: rgba(140, 140, 140, 1);
        line-height: 0.18rem;
        background: rgb(255, 255, 255);
      }
      .active {
        background: rgba(248, 248, 248, 1);
        color: rgba(61, 61, 61, 1);
        &:after {
          content: '';
          height: .26rem;
          border-left: .03rem solid #0080CB;
          position: absolute;
          left: 0;
        }
      }
    }
    .mint-cell-value{
      width: 100%;
    }
  }

</style>
